<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%;">
    <div style="width: 100%;">
      <div style="display: flex; padding: 1px 15px;align-items: center;">
        <el-dropdown trigger="click" popper-class="operation-dropdown" @command="uploadCommand">
          <!-- 组件1 : 新增按钮 + 菜单名称 -->
          <el-button type="primary">新建</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="addfolder">文件夹</el-dropdown-item>
              <el-dropdown-item command="upload">文件</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <span style="margin-left: 10px; font-size: 20px;">文档</span>
        <div style="margin-left: auto;margin-right: auto;" class="search-operation-container">
          <!-- 搜索框 -->
          <ISearch :fieldsConfig="searchDataConfig || []" @searchCallBack="searchCallBack"
                   v-if="multipleSelection.length == 0">
          </ISearch>
          <!-- 操作按钮组 -->
          <div v-else>
            <el-button type="primary" style="background-color: #f1edf0; color: #714B67;">
              {{ "(" + multipleSelection.length + ") 已选取" }}
            </el-button>
            <el-dropdown trigger="click" popper-class="operation-dropdown" @command="handleOperationCommand">
              <el-button type="primary" style="margin-left: 10px;">
                <el-icon>
                  <Tools/>
                </el-icon>
                操作 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="archive">归档</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" style="margin-left: 10px;">分享</el-button>
          </div>
        </div>
        <!-- 按钮组-->
        <IdooButtonGroup :buttonConfigs="buttonGroupDatas" @clickCallBack="buttonGroupChange" is-active-style/>
      </div>
    </div>
    <!-- 分割线 -->
    <el-divider border-style="dotted"/>
    <div style="display: flex;">
      <!-- 部门树 -->
      <div class="main-left-area">
        <div style="padding: 15px">
          <el-icon>
            <Folder/>
          </el-icon>
          <span style="font-size: 15px; font-weight: 600;"> 文档 </span>
        </div>
        <el-tree :data="deptTreeData" :expand-on-click-node="false" :props="defaultProps" node-key="id"
                 @node-click="treeClick">
          <template #default="{ data }">
            <span class="tree-node" :title="data.label">
              <el-icon>
                <Folder/>
              </el-icon>
              {{ data.label }}
            </span>
          </template>
        </el-tree>
      </div>
      <!-- 表格列表 -->
      <div v-if="showType == 'list'"
           style="display: flex;flex-direction: column;  height: auto;position: relative; width: 100%;flex: 1;">
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="type" label="文件类型" width="180">
<!--            <template #default>-->
<!--              <el-icon>-->
<!--                <Folder/>-->
<!--              </el-icon>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column prop="originFileName" label="名称" width="300"/>
          <el-table-column prop="createDept" label="所属部门" sortable width="180"/>
          <el-table-column prop="createTime" label="创建时间" width="180"/>
          <el-table-column prop="size" label="文件大小" width="180"/>
          <el-table-column prop="size" label="下载进度" width="180"/>
          <el-table-column prop="updateTime" label="下载" width="180">
            <template #icon><icon-download /></template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 卡片列表 -->
      <div v-if="showType == 'card'" style="display: flex; flex-direction: column; width: 100%; flex: 1;">
        <div class="card-list-container" ref="cardListContainer">
          <!-- 文件夹 -->
          <div style="display: flex; flex-wrap: wrap; gap: 10px;" v-if="folderData.length > 0">
            <span style="margin-left: 10px; margin-top: 20px;">文件夹</span>
            <el-divider style="margin:-1px 0px 10px 0px !important;" border-style="dotted"/>
            <FolderCard
              v-for="cardItem in folderData"
              :key="cardItem.id"
              :folder-data="cardItem"
              :selected-items="multipleSelection"
              @toggle-selection="toggleCardSelection"
            />
          </div>
          <!-- 文件 -->
          <div style="display: flex; flex-wrap: wrap; gap: 10px;" v-if="fileData.length > 0">
            <span style="margin-left: 10px; margin-top: 20px;">文件</span>
            <el-divider style="margin:-1px 0px 10px 0px !important;" border-style="dotted"/>
            <FileCard
              v-for="cardItem in fileData"
              :key="cardItem.id"
              :file-data="cardItem"
              :selected-items="multipleSelection"
              @toggle-selection="toggleCardSelection"
            />
          </div>
        </div>
      </div>

    </div>
  </div>
  <input type="file" ref="fileInput" @change="onFileSelected" style="display: none;"/>
  <Files :visible="visible"></Files>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {Folder, Tools} from '@element-plus/icons-vue'
import ISearch from '@/components/base/search/index.vue'
import {buttonGroupData, documentTree} from './testData';
import IdooButtonGroup from '@/components/base/button/buttonGroup/index.vue';
import type {ButtonGroupStructure} from '@/components/base/button/buttonGroup';
import type {SearchDataStruct} from '@/components/base/search';
import FolderCard from './components/FolderCard.vue'
import FileCard from './components/FileCard.vue'
import type {FileManage} from '../type';
import Files from "@/views/document/manage/components/files.vue";
import {_list} from "@/api/generic/files/files-api.ts";

//展示方式  list\card
const showType = ref<string>('list')
//列表勾选得内容
const multipleSelection = ref<FileManage[]>([]);
//部门树数据
const deptTreeData = documentTree;
//按钮组数据
const buttonGroupDatas = buttonGroupData;
//搜索框参数
const searchDataConfig = ref<Array<SearchDataStruct>>();
//文件夹数据
const folderData = ref<FileManage[]>([]);
//文件数据
const fileData = ref<FileManage[]>([]);
// 新增：添加文件选择器引用和事件处理函数
const fileInput = ref<HTMLInputElement | null>(null);
// 滚动容器引用
const cardListContainer = ref<HTMLElement | null>(null);
// 数据
const tableData = ref<Files[]>([]);
const visible = defineModel<boolean>('visible')
const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
}
//表格勾选
const handleSelectionChange = (val: []) => {
  console.log(val);
  multipleSelection.value = val
}

const onFileSelected = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;
  if (files) {
    console.log("selected files:", files);
  }
};

const treeClick = (val: object) => {
  console.log(val);
}
//按钮组回调
const buttonGroupChange = (callbackItem: ButtonGroupStructure) => {
  console.log(callbackItem)
  showType.value = callbackItem.id;
  resetViewData();
}
const resetViewData = () => {
  //清空表格勾选数组
  multipleSelection.value = [];
}
//搜索框回调
const searchCallBack = (callbackItem: object) => {
  console.log("搜索回调", callbackItem)
}
//分类 ：区分文件夹或文件
const groupByFileType = (data: FileManage[]) => {
  const folderDatas = data.filter(item => item.fileType == 'folder');
  folderData.value = folderDatas;
  const otherItems = data.filter(item => item.fileType != 'folder');
  fileData.value = otherItems;
}


//init
const dataInit = async () => {
  //列表数据
  const {code, data} = await _list()
  debugger
  if (code === 200) {
    console.log(data)
    debugger
  }
  tableData.value = data;
  //搜索框配置
  searchDataConfig.value = [
    {
      field: 'fileName',
      title: '名称',
      fieldType: 'string',
    },
    {
      field: 'createUserName',
      title: '所有者',
      fieldType: 'string',
    },
    {
      field: 'contacts',
      title: '联系人',
      fieldType: 'string',
    },
    {
      field: 'updateTime',
      title: '上次更新日期',
      fieldType: 'string',
    },
  ]
  //数据分组
  groupByFileType(tableData.value)
}

onMounted(async () => {
  dataInit();
});

const uploadCommand = (command: string) => {
  debugger
  if (command === "upload") {
    visible.value = ref(true)
    // if (fileInput.value) {
    //   fileInput.value.click();
    // }
  } else if (command === "addfolder") {

  }
}
const handleOperationCommand = (command: string) => {
  console.log("操作命令:", command);
  console.log("选中的数据", multipleSelection.value)
  // 根据不同命令执行相应操作
  if (command === "delete") {
    // TODO: 删除操作逻辑
  } else if (command === "export") {
    // TODO: 导出操作逻辑
  } else if (command === "archive") {
    // TODO: 归档操作逻辑
  }
}

// 新增：判断卡片是否被选中
const isCardSelected = (cardItem: FileManage) => {
  return multipleSelection.value.some((item: FileManage) => item.id === cardItem.id);
};

// 新增：切换卡片选中状态
const toggleCardSelection = (cardItem: FileManage) => {
  if (isCardSelected(cardItem)) {
    multipleSelection.value = multipleSelection.value.filter((item: FileManage) => item.id !== cardItem.id);
  } else {
    multipleSelection.value.push(cardItem);
  }
};

// 分片下载文件
// const downloadFile = async (record: Files) => {
//   const index = state.dataSource.findIndex((item) => item.id === record.id)
//   state.dataSource[index].status = 'downloading'
//
//   const totalChunks = Math.ceil(record.size / CHUNK_SIZE) // 请求次数，可自定义调整分片大小，这里默认了上传分片大小
//   // 如果是暂停，根据已下载的，找到断点，偏移长度进行下载
//   const offset = state.blobRef.get(record.id)?.length || 0
//
//   for (let i = offset + 1; i <= totalChunks; i++) {
//     // 暂停/错误 终止后续请求
//     if (state.dataSource[index].status !== 'downloading') return
//
//     const start = CHUNK_SIZE * (i - 1)
//     let end = CHUNK_SIZE * i - 1
//     if (end > record.size) end = record.size // 虽然超出不会影响内容读取，但是会影响进度条的展示
//
//     try {
//       const res = await chunkDownloadFile(record.id, `bytes=${start}-${end}`)
//       const currentDataBlob = state.blobRef.get(record.id) || []
//       // 记录当前数据的分片 blob
//       state.blobRef.set(record.id, [...currentDataBlob, res as unknown as BlobPart])
//       state.dataSource[index].progress = Math.floor((end / record.size) * 100)
//     } catch (error) {
//       state.dataSource[index].status = 'error'
//       return
//     }
//   }
//
//   state.dataSource[index].status = undefined // 重置状态
//   state.dataSource[index].progress = undefined // 重置进度条
//   const blob = new Blob(state.blobRef.get(record.id))
//   downloadFileByBlob(blob, record.originFileName)
// }
</script>

<style scoped>
:deep(.el-divider--horizontal) {
  margin: 20px 0px 0px !important;
}

.main-left-area {
  border-right: 1px solid var(--el-border-color);
  width: 300px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.tree-node {
  color: #333;
  padding: 10px 5px;
  display: block;
}

.tree-count {
  color: #333;
  padding: 10px 5px;
  display: block;
}

.tree-node-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  max-width: 100px;
}

.tree-node-title:hover {
  overflow: visible;
  white-space: normal;
  position: relative;
}

.tree-node-title::after {
  content: attr(title);
  position: absolute;
  left: 0;
  top: 100%;
  background: #000;
  color: #fff;
  padding: 5px;
  display: none;
  z-index: 10;
  white-space: nowrap;
}

.tree-node-title:hover::after {
  display: block;
}

.card-list-container {
  width: 100%;
  background-color: var(--el-bg-color-page);
  overflow-y: auto;
  position: relative;
  padding: 20px;
  height: calc(100vh - 120px);
}

.load-prompt {
  text-align: center;
  padding: 10px;
  background: #f9f9f9;
  color: #888;
  font-size: 14px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

:deep(.operation-dropdown) {
  left: auto !important;
  top: 0 !important;
  transform: translate(100%, 0) !important;
  margin: 0 !important;
}

:deep(.operation-dropdown .el-dropdown-menu) {
  width: auto !important;
  min-width: 100% !important;
  box-sizing: border-box;
}

.search-operation-container {
  height: 32px;
  display: flex;
  align-items: center;
}
</style>
